<template>
  <div class="floating-buttons" :class="{ 'show-top': showBackToTop }">
    <!-- AI小助手按钮 -->
    <el-tooltip content="AI小助手" placement="left" :open-delay="300" :manual="showAiHelper" :disabled="showAiHelper" :enterable="false">
      <div class="ai-btn-container">
        <!-- AI提示气泡 -->
        <transition name="bubble">
          <div v-if="showAiBubble" class="ai-bubble" @click="handleAiBubbleClick">
            {{ aiBubbleMessage }}
            <div class="bubble-close" @click.stop="dismissAiBubble">
              <i class="fas fa-times"></i>
            </div>
          </div>
        </transition>
        <button class="float-btn ai-btn" @click="handleAiButtonClick" title="AI小助手">
          <i class="fas fa-headset"></i>
        </button>
      </div>
    </el-tooltip>

    <el-tooltip content="聊天" placement="left" style="display: none;">
      <router-link to="/chat" class="float-btn chat-btn" title="聊天">
      <i class="fas fa-comments"></i>
    </router-link>
    </el-tooltip>
 
    <el-tooltip content="切换主题" placement="left">
      <button class="float-btn theme-btn" @click="toggleTheme" title="切换主题">
        <i :class="['fas', isDarkMode ? 'fa-sun' : 'fa-moon']"></i>
      </button>
    </el-tooltip>

    <el-tooltip content="回到顶部" placement="left">
      <button 
        v-show="showBackToTop"
        class="float-btn top-btn" 
        @click="scrollToTop"
        title="回到顶部"
      >
        <i class="fas fa-arrow-up"></i>
      </button>
    </el-tooltip>

    <!-- AI小助手对话框 -->
    <el-dialog
      title="AI小助手"
      :visible.sync="showAiHelper"
      width="400px"
      custom-class="ai-helper-dialog"
      :before-close="handleCloseDialog"
      :append-to-body="true"
      :destroy-on-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
    >
      <div class="ai-helper-content">
        <!-- AI聊天记录区域 -->
        <div class="chat-history" ref="chatHistory">
          <div v-for="(msg, index) in chatMessages" :key="index" class="chat-message" :class="{'ai-message': msg.from === 'ai', 'user-message': msg.from === 'user'}">
            <div class="message-content" v-html="formatMessage(msg.content)"></div>
          </div>
          <div v-if="isLoading" class="ai-thinking">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>

        <!-- 快捷问题按钮 -->
        <div class="quick-questions" v-if="chatMessages.length <= 1">
          <button class="quick-btn" @click="askQuestion('如何使用这个网站?')">如何使用这个网站?</button>
          <button class="quick-btn" @click="askQuestion('有什么热门文章推荐?')">有什么热门文章推荐?</button>
          <button class="quick-btn" @click="askQuestion('如何发布评论?')">如何发布评论?</button>
        </div>

        <!-- 输入框区域 -->
        <div class="chat-input">
          <el-input
            v-model="userMessage"
            placeholder="请输入问题..."
            @keyup.enter.native="sendMessage"
            :disabled="isLoading"
          >
            <el-button slot="append" @click="sendMessage" :disabled="isLoading">
              <i class="fas fa-paper-plane"></i>
            </el-button>
          </el-input>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getThemeMode, setThemeMode, initTheme } from '@/utils/theme'
import axios from 'axios'

export default {
  name: 'FloatingButtons',
  data() {
    return {
      isDarkMode: false,
      showBackToTop: false,
      showAiHelper: false,
      showAiBubble: false,
      aiPromptShown: false, // 记录气泡是否已显示过
      userMessage: '',
      chatMessages: [
        {
          from: 'ai',
          content: '👋 嗨！我是AI小助手，可以帮您了解网站功能，解答问题，或推荐适合您的文章。请问有什么可以帮到您的吗？'
        }
      ],
      isLoading: false,
      aiEndpoint: 'https://api.siliconflow.cn/v1/chat/completions',  // SiliconFlow API端点
      recommendedArticles: [],
      aiBubbleMessage: '我是AI小助手，快来找我玩呀！',
      interactionCount: 0,
      bubbleTimer: null,
      bubbleIntervalTimer: null,
    }
  },
  computed: {
    themeIcon() {
      return ['fas', this.isDarkMode ? 'fa-sun' : 'fa-moon']
    }
  },
  watch: {
    chatMessages() {
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    showAiHelper(val) {
      if (val) {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    }
  },
  methods: {
    toggleTheme() {
      this.isDarkMode = !this.isDarkMode
      const mode = this.isDarkMode ? 'dark' : 'light'
      setThemeMode(mode)
    },
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    },
    handleScroll() {
      this.showBackToTop = window.pageYOffset > 300
    },
    scrollToBottom() {
      if (this.$refs.chatHistory) {
        this.$refs.chatHistory.scrollTop = this.$refs.chatHistory.scrollHeight;
      }
    },
    handleCloseDialog(done) {
      // 保存当前对话内容到localStorage，以便下次打开时恢复
      localStorage.setItem('aiChatHistory', JSON.stringify(this.chatMessages));
      
      if (this.interactionCount % 2 === 0) {
        // 偶数次关闭
        this.aiBubbleMessage = '都是渣男，玩完就跑！';
      } else {
        // 奇数次关闭
        this.aiBubbleMessage = '这么快就不要人家了，不要走/(ㄒoㄒ)/~~';
      }
      
      // 显示离别消息
      this.showAiBubble = true;
      
      // 5秒后自动隐藏
      clearTimeout(this.bubbleTimer);
      this.bubbleTimer = setTimeout(() => {
        this.showAiBubble = false;
        // 重置为默认消息，为下次显示准备
        this.aiBubbleMessage = '我是AI小助手，快来找我玩呀！';
      }, 5000);
      
      // 确保调用done函数关闭对话框
      if (typeof done === 'function') {
        done();
      }
    },
    askQuestion(question) {
      this.userMessage = question;
      this.sendMessage();
    },
    sendMessage() {
      if (!this.userMessage.trim() || this.isLoading) return;
      
      // 添加用户消息
      this.chatMessages.push({
        from: 'user',
        content: this.userMessage
      });
      
      // 清空输入框
      const userQuestion = this.userMessage;
      this.userMessage = '';
      
      // 设置加载状态
      this.isLoading = true;
      
      // 获取当前页面信息和用户上下文
      const currentPath = this.$route.path;
      const currentPathName = this.$route.name || '首页';
      const userContext = this.$store.state.userInfo ? `用户已登录，用户名：${this.$store.state.userInfo.nickname}` : '用户未登录';
      
      // 构建完整的上下文
      const contextMessages = [
        {
          role: "system",
          content: `你是一个博客网站的AI小助手，名叫"智能助手"。你的主要任务是：
1. 帮助用户了解网站功能，提供操作指引
2. 回答用户关于博客内容的问题
3. 推荐适合用户的文章
4. 解答技术问题

当前页面信息：路径=${currentPath}，页面=${currentPathName}
${userContext}

请保持回答友好、专业、简洁。如果不确定的问题，可以建议用户查看相关文档或联系管理员。`
        }
      ];
      
      // 添加历史对话作为上下文
      this.chatMessages.forEach(msg => {
        if (msg.from === 'ai') {
          contextMessages.push({ role: "assistant", content: msg.content });
        } else if (msg.from === 'user') {
          contextMessages.push({ role: "user", content: msg.content });
        }
      });
      
      // 安全处理API密钥
      // 注意：在生产环境中，应该通过后端代理转发请求，而不是直接在前端使用API密钥
      const apiKey = 'sk-vtyikbtifutklfoqyvtztqkiverladsixghbzrqvhembjfbz'; 
      
      // 调用SiliconFlow API
      axios({
        method: 'post',
        url: this.aiEndpoint,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`
        },
        data: {
          model: "deepseek-ai/DeepSeek-R1-0528-Qwen3-8B", // 使用指定的模型
          messages: contextMessages,
          stream: false,
          max_tokens: 1000,
          temperature: 0.7,
          top_p: 0.7,
          top_k: 50,
          frequency_penalty: 0.5,
          n: 1,
          response_format: {
            type: "text"
          }
        }
      })
      .then(response => {
        console.log('AI响应:', response.data);
        
        if (response.data && response.data.choices && response.data.choices.length > 0) {
          let aiReply = response.data.choices[0].message.content;
          
          // 检查用户问题是否包含"推荐"或"文章"
          if (userQuestion.includes('推荐') || userQuestion.includes('文章')) {
            // 添加推荐文章链接
            const recommendedLinks = [
              'http://web.zyxlfl.top/post/375',
              'http://web.zyxlfl.top/post/362',
              'http://web.zyxlfl.top/post/344'
            ];
            
            // 确保AI回复中包含这些链接
            if (!aiReply.includes('http://web.zyxlfl.top/post/')) {
              aiReply += '\n\n以下是一些推荐的博客文章链接：\n';
              recommendedLinks.forEach((link, index) => {
                aiReply += `${index + 1}. ${link}\n`;
              });
            }
          }
          
          // 添加AI回复
          this.chatMessages.push({
            from: 'ai',
            content: aiReply
          });
          
          // 如果回复中包含文章推荐，可以提取并展示
          if (aiReply.includes('推荐阅读') || aiReply.includes('推荐文章')) {
            // 这里可以进一步处理推荐结果，例如提取文章链接等
          }
        } else {
          throw new Error('AI响应格式不正确');
        }
      })
      .catch(error => {
        console.error('AI API调用错误:', error);
        
        // 显示错误消息
        this.chatMessages.push({
          from: 'ai',
          content: '抱歉，我遇到了一些技术问题。请稍后再试或联系网站管理员。'
        });
      })
      .finally(() => {
        this.isLoading = false;
      });
    },
    fallbackAIResponse(question) {
      // 这是模拟AI响应的函数，在API调用失败时使用
      let response = '';
      
      if (question.includes('使用') || question.includes('功能')) {
        response = '这个网站主要有博客阅读、评论互动、资源下载等功能。您可以点击顶部导航栏浏览不同分类的内容。登录后还可以收藏文章、参与讨论。';
      } else if (question.includes('文章') || question.includes('推荐')) {
        response = '根据最近的阅读数据，推荐您阅读以下文章：\n1. http://web.zyxlfl.top/post/375\n2. http://web.zyxlfl.top/post/362\n3. http://web.zyxlfl.top/post/344\n点击链接可以直接跳转阅读。';
      } else if (question.includes('评论')) {
        response = '要发布评论，首先需要登录账号。然后在文章底部的评论区输入您的想法，点击"提交"按钮即可发布。请注意遵守社区规则哦！';
      } else {
        response = '感谢您的提问！我可以帮您了解网站功能、推荐内容，或解答使用问题。如果您想了解特定主题的文章，也可以告诉我您感兴趣的领域。';
      }
      
      return response;
    },
    // 处理AI气泡点击
    handleAiBubbleClick() {
      this.interactionCount++;
      
      if (this.interactionCount === 1 || this.interactionCount % 2 === 1) {
        // 第一次点击或奇数次点击
        this.aiBubbleMessage = '嘻嘻，又回来啦';
      }
      
      this.showAiHelper = true;
    },
    
    // 处理AI按钮点击
    handleAiButtonClick() {
      this.interactionCount++;
      this.showAiHelper = true;
    },
    
    // 关闭AI提示气泡
    dismissAiBubble() {
      this.showAiBubble = false;
      // 存储到localStorage，记录用户已关闭过气泡
      localStorage.setItem('aiPromptDismissed', 'true');
    },
    
    // 显示AI提示气泡的定时器
    scheduleAiPrompt() {
      // 检查是否已经显示过或用户已关闭过
      const dismissed = localStorage.getItem('aiPromptDismissed') === 'true';
      
      if (!dismissed) {
        // 首次访问立即显示提示
        this.showAiBubble = true;
        this.aiPromptShown = true;
        
        // 5秒后自动隐藏
        this.bubbleTimer = setTimeout(() => {
          this.showAiBubble = false;
        }, 5000);
        
        // 每隔7秒显示一次，显示5秒
        this.bubbleIntervalTimer = setInterval(() => {
          if (!this.showAiHelper) { // 如果AI助手未打开才显示提示
            this.aiBubbleMessage = '我是AI小助手，快来找我玩呀！';
            this.showAiBubble = true;
            
            // 5秒后自动隐藏
            clearTimeout(this.bubbleTimer);
            this.bubbleTimer = setTimeout(() => {
              this.showAiBubble = false;
            }, 5000);
          }
        }, 7000);
      }
    },
    formatMessage(content) {
      // 将URL转换为可点击的链接
      return content.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer" class="message-link">$1</a>');
    }
  },
  mounted() {
    this.isDarkMode = initTheme()
    window.addEventListener('scroll', this.handleScroll)
    
    // 尝试从localStorage恢复对话历史
    try {
      const savedChat = localStorage.getItem('aiChatHistory');
      if (savedChat) {
        const parsedChat = JSON.parse(savedChat);
        // 确保解析出的数据是数组且至少有一条消息
        if (Array.isArray(parsedChat) && parsedChat.length > 0) {
          this.chatMessages = parsedChat;
        }
      }
    } catch (e) {
      console.error('恢复对话历史失败:', e);
      // 出错时使用默认欢迎消息
    }
    
    // 初始化AI提示气泡
    this.scheduleAiPrompt();
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
    // 清除所有定时器
    clearTimeout(this.bubbleTimer);
    clearInterval(this.bubbleIntervalTimer);
  }
}
</script>

<style lang="scss" scoped>
.floating-buttons {
  position: fixed;
  right: 20px;
  bottom: 100px;
  display: flex;
  flex-direction: column;
  gap: $spacing-sm;
  z-index: 1000;
}

.ai-btn-container {
  position: relative;
}

.ai-bubble {
  position: absolute;
  right: 50px;
  top: 0;
  width: 200px;
  padding: 10px 15px;
  background: linear-gradient(135deg, #4CAF50, #8BC34A);
  color: white;
  border-radius: 12px;
  font-size: 14px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1001;
  animation: wobble 1s ease-in-out;
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  
  &:hover {
    transform: scale(1.05);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
  }
  
  &::after {
    content: '';
    position: absolute;
    right: -8px;
    top: 15px;
    width: 0;
    height: 0;
    border-top: 8px solid transparent;
    border-bottom: 8px solid transparent;
    border-left: 8px solid #8BC34A;
  }
  
  .bubble-close {
    position: absolute;
    top: 5px;
    right: 5px;
    width: 16px;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 10px;
    opacity: 0.8;
    
    &:hover {
      opacity: 1;
    }
  }
}

@keyframes wobble {
  0% {
    transform: translateX(20px);
    opacity: 0;
  }
  50% {
    transform: translateX(-5px);
  }
  70% {
    transform: translateX(3px);
  }
  100% {
    transform: translateX(0);
    opacity: 1;
  }
}

.bubble-enter-active {
  animation: wobble 0.5s;
}

.bubble-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.bubble-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

.float-btn {
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 50%;
  background: var(--card-bg);
  color: var(--text-primary);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: $shadow-lg;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  opacity: 0.8;

  &:hover {
    opacity: 1;
    transform: translateY(-2px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  }

  &.chat-btn {
    background: $primary;
    color: white;
    text-decoration: none;
    animation: pulse 2s infinite;
    &:hover {
      background: darken($primary, 10%);
    }
  }

  &.ai-btn {
    background: linear-gradient(135deg, #4CAF50, #8BC34A);
    color: white;
    animation: aiBounce 3s infinite;
    
    i {
      font-size: 1.3em;
    }
  }

  &.theme-btn {
    background: linear-gradient(135deg, $primary, $secondary);
    color: white;
   
  }
  

  &.top-btn {
    transform: translateY(100px);
    opacity: 0;
    visibility: hidden;
    background: var(--card-bg);
    border: 1px solid var(--border-color);

    .show-top & {
      transform: translateY(0);
      opacity: 0.8;
      visibility: visible;
      animation: bounceIn 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    }
  }

  i {
    font-size: 1.2em;
  }
}

@keyframes bounceIn {
  0% {
    transform: translateY(100px) scale(0.3);
    opacity: 0;
  }
  50% {
    transform: translateY(-10px) scale(1.1);
  }
  70% {
    transform: translateY(5px) scale(0.95);
  }
  100% {
    transform: translateY(0) scale(1);
    opacity: 0.8;
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba($primary, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba($primary, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba($primary, 0);
  }
}

@keyframes aiBounce {
  0%, 100% {
    transform: translateY(0);
  }
  5% {
    transform: translateY(-5px);
  }
  10% {
    transform: translateY(0);
  }
  15% {
    transform: translateY(-3px);
  }
  20% {
    transform: translateY(0);
  }
}

.ai-helper-dialog {
  border-radius: 12px;
  overflow: hidden;
  
  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #4CAF50, #8BC34A);
    padding: 15px 20px;
    
    .el-dialog__title {
      color: white;
      font-weight: 500;
    }
    
    .el-dialog__headerbtn .el-dialog__close {
      color: white;
    }
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.ai-helper-content {
  display: flex;
  flex-direction: column;
  height: 500px;
}

.chat-history {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background: var(--card-bg);
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.chat-message {
  max-width: 80%;
  padding: 10px 15px;
  border-radius: 18px;
  margin-bottom: 5px;
  
  &.ai-message {
    align-self: flex-start;
    background: #f0f0f0;
    border-bottom-left-radius: 5px;
    color: #333;
  }
  
  &.user-message {
    align-self: flex-end;
    background: linear-gradient(135deg, #4CAF50, #8BC34A);
    border-bottom-right-radius: 5px;
    color: white;
  }
  
  .message-content {
    white-space: pre-line;
    
    .message-link {
      color: inherit;
      text-decoration: underline;
      word-break: break-all;
      
      &:hover {
        opacity: 0.8;
      }
    }
  }
}

.ai-thinking {
  align-self: flex-start;
  margin-bottom: 5px;
}

.typing-indicator {
  display: inline-flex;
  align-items: center;
  background: #f0f0f0;
  padding: 8px 12px;
  border-radius: 18px;
  
  span {
    height: 8px;
    width: 8px;
    background: #aaa;
    border-radius: 50%;
    display: block;
    margin: 0 2px;
    opacity: 0.6;
    
    &:nth-child(1) {
      animation: blink 1s infinite 0s;
    }
    
    &:nth-child(2) {
      animation: blink 1s infinite 0.2s;
    }
    
    &:nth-child(3) {
      animation: blink 1s infinite 0.4s;
    }
  }
}

@keyframes blink {
  0%, 100% {
    opacity: 0.6;
    transform: scale(1);
  }
  50% {
    opacity: 1;
    transform: scale(1.2);
  }
}

.chat-input {
  padding: 15px;
  border-top: 1px solid #eee;
  background: var(--card-bg);
}

.quick-questions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 0 15px 15px;
  background: var(--card-bg);
}

.quick-btn {
  background: #f0f0f0;
  border: none;
  padding: 8px 12px;
  border-radius: 16px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    background: #e0e0e0;
  }
}

@include responsive(sm) {
  .floating-buttons {
    right: 15px;
    bottom: 80px;
  }

  .float-btn {
    width: 36px;
    height: 36px;
  }
  
  .ai-helper-dialog {
    width: 95% !important;
    margin-top: 20vh !important;
  }
  
  .ai-helper-content {
    height: 400px;
  }
}
</style>

<style>
/* 全局样式，修复dialog z-index问题 */
.ai-helper-dialog {
  z-index: 2001 !important; /* 确保对话框显示在最上层 */
}

.v-modal {
  z-index: 0;
   /* 确保遮罩层正确显示 */
}
</style> 